﻿#include "SingleLinedList.h"

// 无头单链表-工具函数
// 动态申请节点
ListNode* BuyListNode(DataType elem)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	node->data = elem;
	node->next = NULL;
	return node;
}


// 无头单链表-基本操作函数
// 单链表头部插入
void SingleListPushFront(ListNode** list, DataType elem)
{
	assert(list);
	ListNode* node = BuyListNode(elem);
	node->next = (*list);
	(*list) = node;
}
// 单链表头部删除
void SingleListPopFront(ListNode** list)
{
	assert(list);
	assert(*list);
	ListNode* next = (*list)->next;
	free(*list);
	(*list) = next;
}
// 单链表尾部插入
void SingleListPushBack(ListNode** list, DataType elem)
{
	assert(list);
	if (*list)
	{
		ListNode* tail = (*list);
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = BuyListNode(elem);
	}
	else
	{
		(*list) = BuyListNode(elem);
	}
}
// 单链表尾部删除
void SingleListPopBack(ListNode** list)
{
	assert(list);
	assert(*list);
	if ((*list)->next == NULL)
	{
		free(*list);
		(*list) = NULL;
	}
	else
	{
		ListNode* prev = NULL;
		ListNode* tail = (*list);
		while (tail->next)
		{
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		prev->next = NULL;
	}
}
// 单链表pos位置后插入x
void SingleListInsertAfter(ListNode** list, size_t pos, DataType elem)
{
	assert(list);
	assert(pos < SingleListLength(*list));
	ListNode* cur = (*list);
	for (int i = 0; i < pos; i++)
	{
		cur = cur->next;
	}
	ListNode* node = BuyListNode(elem);
	node->next = cur->next;
	cur->next = node;
}
// 单链表删除pos位置后元素
void SingleListEraseAfter(ListNode** list, size_t pos)
{
	assert(list);
	assert(pos < SingleListLength(*list) - 1);
	ListNode* cur = (*list);
	for (int i = 0; i < pos; i++)
	{
		cur = cur->next;
	}
	ListNode* del = cur->next;
	cur->next = cur->next->next;
	free(del);
}
// 单链表查找元素 - 返回对应元素节点
ListNode* SingleListFind(ListNode* list, DataType data) 
{
	assert(list);
	while (list != NULL)
	{
		if (list->data == data)
		{
			return list;
		}
	}
	return NULL;
}
// 单链表长度
size_t SingleListLength(ListNode* list)
{
	assert(list);
	size_t count = 0;
	while (list) 
	{
		count++;
		list = list->next;
	}
	return count;
}
// 遍历单链表
void SingleListTraverse(ListNode* list)
{
	while (list) 
	{
		printf("%d->", list->data);
		list = list->next;
	}
	printf("NULL\n");
}